package cn.yuxiaoyuan.article.service.impl;

import cn.yuxiaoyuan.article.domain.ArticleType;
import cn.yuxiaoyuan.article.mapper.ArticleTypeMapper;
import cn.yuxiaoyuan.article.query.ArticleTypeQuery;
import cn.yuxiaoyuan.article.service.ArticleTypeService;
import cn.yuxiaoyuan.article.vo.ArticleTypeVo;
import cn.yuxiaoyuan.base.service.impl.BaseServiceImpl;
import cn.yuxiaoyuan.constant.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ArticleTypeServiceImpl extends BaseServiceImpl<ArticleType> implements ArticleTypeService {
    @Autowired
    private ArticleTypeMapper articleTypeMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public List<ArticleType> queryPage(ArticleTypeQuery query) {
        return articleTypeMapper.queryPage(query);
    }

    @Override
    @Cacheable(cacheNames = "articleType", key = "'typeTree'")
    public List<ArticleTypeVo> articleTypeTree() {
        //判断redis中key是否存在   存在返回true
//        if (redisTemplate.hasKey(RedisConstant.ARTICLE_TYPE_TREE)) {
//            return  (List<ArticleTypeVo>)redisTemplate.opsForValue().get(RedisConstant.ARTICLE_TYPE_TREE);
//        }
        //原始数据
        List<ArticleType> types = articleTypeMapper.findAll();
        //变成了ArticleTypeVo == 没有发生改变的
        List<ArticleTypeVo> typeVos = types.stream().map(type -> {
            ArticleTypeVo articleTypeVo = new ArticleTypeVo();
            articleTypeVo.setValue(type.getId());
            articleTypeVo.setParentId(type.getParentId());
            articleTypeVo.setLabel(type.getTypeName());
            return articleTypeVo;
        }).collect(Collectors.toList());
        //将value作为key  将ArticleTypeVo作为值
        Map<Long,ArticleTypeVo> typeVoMap = new HashMap<>();
        for (ArticleTypeVo typeVo : typeVos) {
            typeVoMap.put(typeVo.getValue(),typeVo);
        }
        //准备返回对象
        List<ArticleTypeVo> typeList = new ArrayList<>();
        //进行多层级封装
        for (ArticleTypeVo typeVo : typeVos) {
            //有ParentId 和没有 ParentId
            if(typeVo.getParentId() == null){ //没有就是顶级
                typeList.add(typeVo);
            }else {//找你的爹
                ArticleTypeVo articleTypeVo = typeVoMap.get(typeVo.getParentId());
                //将你放入你的爹里面
                articleTypeVo.getChildren().add(typeVo);
            }
        }
        //存放redis
//        redisTemplate.opsForValue().set(RedisConstant.ARTICLE_TYPE_TREE,typeList);
        return typeList;
    }
}
